<?php

namespace app\api\controller;

use addons\faqueue\library\QueueApi;
use app\common\controller\Api;
use think\Cache;
use think\Db;
use app\api\model\Activity;
use app\api\model\Coupon;
use think\Log;
use think\Request;
use wxpay\lspay;
use wxpay\wxpay;
use alipay\Alipay;
use fast\Http;
use epay\epay;
use Monolog\Handler\DynamoDbHandler;
use think\Console;
use app\common\model\User;
use app\common\model\Recharge;
use app\common\model\Balancelog;
use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['getSettingkf', 'getHd', 'getCoupon', 'getBoxlist', 'getSite', 'getSetting', 'getCards', 'notifyx','notifyx2', 'mhnotifyx', 'getApp', 'SgetOne', 'index', 'getBarrage','notifyxThree','getpaystatus'];
    protected $noNeedRight = ['*'];

    /*设置信息*/
    public function getBarrage()
    {
        $s = Db::table('box_barrage')->select();
        $this->success('查询成功', $s);
    }

    /*设置信息*/
    public function getSettingkf()
    {
        $s = Db::table('box_setting')->where('id', 1)->find();
        $s['kfimage'] = cdnurl($s['kfimage'], true);
        $s['logo'] = cdnurl($s['logo'], true);
        $this->success('查询成功', $s);
    }
    //原始微信支付费用
    public function payJoinfee2($name, $ooid, $price)
    {
        $s = Db::table('box_setting')->where('id', 1)->find();
        $appid = $s['mpappid'];
        $openid = $this->auth->wx_mini_openid;
        $mch_id = $s['payid'];
        $key = $s['paykey'];
        $notifyurl = $this->request->domain() . '/index.php/api/index/notifyx2';
        $weixinpay = new wxpay($appid, $openid, $mch_id, $key, $name, $ooid, $price, $notifyurl);
        $return = $weixinpay->pay();
        $this->success('支付', ['data' => $return, 'ooid' => $ooid]);
    }
    //原始微信支付费用
    public function payJoinfee($name, $ooid, $price)
    {
        $s = Db::table('box_setting')->where('id', 1)->find();
        $appid = $s['mpappid'];
        $openid = $this->auth->wx_mini_openid;
        $mch_id = $s['payid'];
        $key = $s['paykey'];
        // import('Weixin.Lib.WeixinPay');
        $notifyurl = $this->request->domain() . '/index.php/api/index/notifyx';
        $weixinpay = new wxpay($appid, $openid, $mch_id, $key, $name, $ooid, $price, $notifyurl);
        $return = $weixinpay->pay();
        $this->success('支付', ['data' => $return, 'ooid' => $ooid]);
    }
    //联速三方支付费用
    public function payJoinfeeThree($name, $ooid, $price)
    {
        log::write(["msg"=>"payJoinfeeThree","data"=>$ooid],"log");
        $s = Db::table('box_setting')->where('id', 1)->find();
        $mch_id = $s['lspay_mch_no'];
        $key = $s['lspay_key'];
        $app_id = $s['lspay_app_id'];
        $openid = $this->auth->wx_mini_openid;
        $notifyurl = $this->request->domain() . '/index.php/api/index/notifyxThree';
        $weixinpay = new lspay($openid, $mch_id, $key, $app_id, $name, $ooid, $price, $notifyurl);
        $return = $weixinpay->pay();
        $this->success('支付', ['data' => $return, 'ooid' => $ooid]);
    }
    /**
     * 获取活动专区
     */
    public function getHd()
    {
        $hd =  Activity::getHd();
        if (empty($hd)) {
            $this->error('暂无活动');
        } else {
            foreach ($hd as &$hd_v) {
//                $hd_v['activityimage_v'] = cdnurl($hd_v['activityimage'], true);
                $hd_v['tcimage'] = cdnurl($hd_v['tcimage'], true);
            }
            $this->success('查询成功', $hd);
        }
    }
    /**
     * 获取优惠券
     */
    public function getCoupon()
    {
        //获取全部优惠券
        $coupon = Coupon::getCou();
        if (empty($coupon)) {
            $this->error('暂无可领取优惠券');
        }
        //   print_r($this->auth->id);
        //   exit;
        //获取已经领取的优惠券
        $coupon_list = Db::table('box_coupon_list')->where('user_id', $this->auth->id)->select();
        // print_r($coupon_list);
        // exit;
        if (!empty($coupon_list)) {
            foreach ($coupon as &$a) {
                foreach ($coupon_list as $b) {
                    if ($b['coupon_id'] == $a['id']) {
                        $a['status_a'] = 1;
                    } else {
                        if (empty($a['status_a'])) {
                            $a['status_a'] = 0;
                        }
                    }
                }
            }
        } else {
            foreach ($coupon as &$c) {
                $c['status_a'] = 0;
            }
        }
        $this->success('优惠券列表', $coupon);
    }
    /**
     * 获取开箱记录
     */
    public function getBoxlist()
    {
        //查询所有盒柜商品
        $list = Db::table('box_mhlog')->order('addtime DESC')->page(1, 10)->select();
        $id = [];
        foreach ($list as $list_v) {
            $id[] = $list_v['mhgoods_id'];
        }
        $shops = Db::table('box_mhgoods')->where('id', 'in', $id)->select();
        // print_r($shops);
        // exit;
        foreach ($list as &$list_a) {
            $list_a['mhimage'] = cdnurl($list_a['mhimage'], true);
            foreach ($shops as $shop) {
                if ($list_a['mhgoods_id'] == $shop['id']) {

                    $list_a['gl'] = $shop['tag'];
                }
            }
        }
        $this->success('开箱记录', $list);
    }
    /**
     * 获取 新手教程
     */
    public function getSetting()
    {
        $s = Db::table('box_setting')->where('id', 1)->find();
        // print_r($s);
        // exit;
        $s['kfimage'] = cdnurl($s['kfimage'], true);
        $arr = [
            'kfimg' => $s['kfimage'],
            'xsjc' => $s['tutorialfile']
        ];
        $this->success('查询成功', $arr);
    }
    
    
    /**
     * 开盲盒支付
     */
    public function goRecharge()
    {
        $post = input('post.');
        // $ooid = 'ALDMH' . date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        list($msec, $sec) = explode(' ', microtime());
        $num = md5(floatval($msec) + floatval($sec).time());
        $ooid = 'ALDMH' . date('Ymd') . substr(md5(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))).$num), 0, 8);
        $data = [
            'user_id' => $this->auth->id,
            'pay_method' => $post['payfs'],
            'pay_coin' => $post['price'],
            'out_trade_no' => $ooid,
            'status' => 'unpay', //unpay=待支付,used=已使用,refund=已关闭
            'addtime' => time(),
            'terminal' => $post['terminal'],
        ];
        $recharge = (new Recharge())->insert($data);
        /**
         * 判断来源
         * 0：H5
         * 1：小程序
         * 2：APP
         */
        if ($post['terminal'] == 0) {
            //如果为0就是H5
            return $this->error("H5支付暂未开通");
        } else if ($post['terminal'] == 1) {
            $epay = new epay;
            // 如果为1就是小程序---这里只有微信支付了
            if ($post['payfs'] != 'balance') {
                $payWay = Cache::get("pay_way");
                if(!$payWay){
                    $payWay = Db::table("box_setting")->where("id",1)->column("pay_way");
                    $payWay = $payWay[0];
                }
                //1.微信原生支付；2.联速支付
                if($payWay == 1){
                    log::write(["msg"=>"微信原生支付","data"=>$payWay],"log");
                    // $post['price'] = 0.01;
                    $this->payJoinfee2('软件服务费', $ooid, $post['price']);
                }else{
                    return $this->error("联速支付暂未开通");
                    // log::write(["msg"=>"联速支付","data"=>$payWay],"log");
                    // $this->payJoinfeeThree('欧币充值', $ooid, $post['price']);//微信支付改用第三方套皮调起
                }
            }else{
                $this->error('支付方式有问题',['ooid'=>$ooid]);
            }
        } else if ($post['terminal'] == 2) {
            return $this->error("App支付暂未开通");
        }
    }
    
    
    
    
       /**
     * 虚拟支付
     */
    public function goRechargexuni()
    {
        $post = input('post.');
        // $ooid = 'ALDMH' . date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        list($msec, $sec) = explode(' ', microtime());
        $num = md5(floatval($msec) + floatval($sec).time());
        $ooid = 'ALDMH' . date('Ymd') . substr(md5(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))).$num), 0, 8);
        
        
         $user = User::where('id',$this->auth->id)->find();
         if(!$user->anchor_switch){
             $this->error('支付方式有问题',['ooid'=>$ooid]); 
         }
        $data = [
            'user_id' => $this->auth->id,
            'pay_method' => $post['payfs'],
            'pay_coin' => $post['price'],
            'out_trade_no' => $ooid,
            'status' => 'unpay', //unpay=待支付,used=已使用,refund=已关闭
            'addtime' => time(),
            'terminal' => $post['terminal'],
        ];
        $recharge = (new Recharge())->insert($data);
        $recharge = Recharge::where('out_trade_no',$ooid)->where('status','unpay')->find();
        if($recharge) {
               $user = User::where('id',$recharge->user_id)->find();
               $after_price = bcadd($user->balance,$recharge->pay_coin,2);
               $time = time();
               
               $recharge->pay_time = $time;
               $recharge->after_balace = $after_price;
               $recharge->transaction_id = '0';
               $recharge->status = 'used';
               $recharge->save(); 
               
              $ret = Db::table('box_balancelog')->insert([
                    'user_id'=> $recharge->user_id,
                    'beforemoney'=> $user->balance,
                    'aftermoney'=> $after_price,
                    'money'=> $recharge->pay_coin,
                    'bgexplain' => 'obcz',
                    'addtime' => time(),
              ]);
               
               $user->balance = $after_price;
               if($user->save()){
                    $this->success('支付成功',['ooid'=>$ooid]);
               }
            }
         $this->error('支付方式有问题',['ooid'=>$ooid]);
       
    }
    
    
    
    
    
    // 设置参数
    private function getOptions()
    {
        $s = Db::table('box_setting')->where('id', 1)->find();
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = $s['appId'];
        $options->merchantPrivateKey = $s['rsaPrivateKey'];
        $options->alipayPublicKey = $s['alipayrsaPublicKey'];
        return $options;
    }
    
    /**
     * 开盲盒支付
     */
    public function goPay()
    {
        log::write(["msg"=>"进日志了吗?"],"log");
        $post = input('post.');
        // $ooid = 'ALDMH' . date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        list($msec, $sec) = explode(' ', microtime());
        $num = md5(floatval($msec) + floatval($sec).time());
        $ooid = 'ALDMH' . date('Ymd') . substr(md5(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))).$num), 0, 8);
        $box = Db::table('box_boxfl')->where('id', $post['boxid'])->find();
        if(empty($box)){ $this->error('盲盒不存在'); } 
        $user = User::where('id',$this->auth->id)->find();
        
        $data = [
            'boxfl_id' => $post['boxid'],
            'boxfl_name' => $box['box_name'],
            'image' => $box['box_banner_images'],
            'num' => $post['num'],
            'user_id' => $this->auth->id,
            'pay_method' => $post['payfs'],
            'pay_coin' => $post['price'],
            'out_trade_no' => $ooid,
            'status' => 'unpay', //unpay=待支付,used=已使用,refund=已关闭
            'create_time' => time(),
            'terminal' => $post['terminal'],
            'xingshi' => $post['xs'],
            'ischou' => 0,
            'anchor_switch'=> $user->anchor_switch
        ];

        $oid = Db::table('box_order')->insertGetId($data);
//
//        if (!empty($oid)) {
//            if (!empty($post['couid'])) {
//                Db::table('box_coupon_list')->where('id', $post['couid'])->update(['status' => 1, 'sytime' => time()]);
//            }
//        }
        /*判断余额支付*/
        if($post['payfs'] == 'balance'){
            $ret = Db::table('box_order')->where('id',$oid)->update(['status' => 'used', 'pay_time' => time()]);
            $user = Db::table('box_user')->where('id',$this->auth->id)->find();
            $s = Db::table('box_setting')->where('id',1)->find();
            if ($post['price']>$user['balance']) {
                $this->error('支付失败，您的余额不足');
                exit();
            }
            if($post['price']!=0 || $post['xs'] > 0){
                 $ret = Db::table('box_balancelog')->insert([
                        'user_id'=> $this->auth->id,
                        'beforemoney'=> $user['balance'],
                        'aftermoney'=> $user['balance'] - $post['price'],
                        'money'=> $post['price'],
                        'bgexplain' => 'gmgh',
                        'addtime' => time(),
                  ]);
                
                // Db::table('box_user')->where('id', $this->auth->id)->update(['money' => $user['money'] - $post['xs']]);
                Db::table('box_user')->where('id', $this->auth->id)->update(['balance' => $user['balance'] - $post['price']]);
                // Db::table('box_balancelog')->insert([
                //     'user_id' => $this->auth->id,
                //     'beforemoney' => $user['balance'],
                //     'aftermoney' => $user['money'] - $post['xs'],
                //     'money' => $post['xs'],
                //     'bgexplain' => 'dikou',
                //     'addtime' => time()
                // ]);
                self::handle($ooid,0,$post['zb_rule_open']);
                $this->success('支付成功',['ooid'=>$ooid]);
            }
        }
        /**
         * 判断来源
         * 0：H5
         * 1：小程序
         * 2：APP
         */
        if ($post['terminal'] == 0) {
            //如果为0就是H5
            $epay = new epay;
            if ($post['payfs'] == 'alipay') {
                // $notifyurl = $this->request->domain() . '/index.php/api/pay/epaymhnotifyx';
                // $epay->goePay($ooid, 'alipay', '软件服务费', $post['price'],$notifyurl,$this->request->domain() . '/h5/#/pages/home/luckbox?ooid='.$ooid . '&num='.$post['num'].'&boxid='.$post['boxid']);
                if($post['price'] == 0){
                    self::handle($ooid,0);
                    $this->success('支付成功',['ooid'=>$ooid]);
                    echo json_encode(['code'=>1,'data'=>[''],'ooid'=>$ooid]); //就是orderString 可以直接给客户端请求，无需再做处理。
                }else {
                    $alipay = new Alipay();
                    $notice = $this->request->domain() . '/index.php/api/index/mhnotifyx';
                    $alipay->h5pay('软件服务费', $ooid, $post['price'], $notice,$this->request->domain() . '/h5/#/pages/home/luckbox?ooid='.$ooid . '&num='.$post['num'].'&boxid='.$post['boxid']);   
                }
            }else if($post['payfs'] == 'wechat'){
                $notifyurl = $this->request->domain() . '/index.php/api/pay/epaymhnotifyx';
                $epay->goePay($ooid, 'wechat', '软件服务费', $post['price'],$notifyurl,$this->request->domain() . '/h5/#/pages/home/luckbox?ooid='.$ooid . '&num='.$post['num'].'&boxid='.$post['boxid']);
            }
        } else if ($post['terminal'] == 1) {
            $epay = new epay;
            // 如果为1就是小程序---这里只有微信支付了
            if ($post['payfs'] != 'balance') {
                if($post['payfs'] == 'alipay') {
                    if($post['price'] < 0 || ($post['price'] == 0 && $post['xs'] <= 0)){
                        $this->error("页面错误，请刷新页面");
                    }elseif ($post['price'] == 0){
                        self::handle($ooid,0,$post['zb_rule_open']);
                        $this->success('支付成功',['ooid'=>$ooid]);
                    }
                    $alipay = new Alipay();
                    $notice = $this->request->domain() . '/index.php/api/index/mhnotifyx';
                    // $alipay->mppay('抽取盲盒', $ooid, $post['price'], $notice,$this->auth->ali_mini_userid);
                    Factory::setOptions($this->getOptions());
                    // try {
                        // $post['price'] = 0.01;
                        $result = Factory::payment()->common()
                            ->asyncNotify($notice)
                            ->create("抽取盲盒", $ooid,$post['price'], $this->auth->ali_mini_userid);
                        if (!empty($result->code) && $result->code == 10000) { 
                            $this->success('支付成功',['ooid'=>$ooid,'tradeNo'=>$result->tradeNo]);
                        } else {
                            $this->error('支付异常',['ooid'=>$ooid]);
                        }
                    // }catch (\Exception $e) {
                    //     halt($e->getMessage());die();
                    //     // echo "调用失败，". $e->getMessage(). PHP_EOL;
                    //     $this->error('支付异常',['ooid'=>$ooid]);
                    // }
                }else {
                    if($post['price'] < 0 || ($post['price'] == 0 && $post['xs'] <= 0)){
                        $this->error("页面错误，请刷新页面");
                    }elseif ($post['price'] == 0){
                        self::handle($ooid,0,$post['zb_rule_open']);
                        $this->success('支付成功',['ooid'=>$ooid]);
                    }
                    $payWay = Cache::get("pay_way");
                    if(!$payWay){
                        $payWay = Db::table("box_setting")->where("id",1)->column("pay_way");
                        $payWay = $payWay[0];
                    }
                    //1.微信原生支付；2.联速支付
                    if($payWay == 1){
                        log::write(["msg"=>"微信原生支付","data"=>$payWay],"log");
                        $this->payJoinfee('软件服务费', $ooid, $post['price']);
                    }else{
                        log::write(["msg"=>"联速支付","data"=>$payWay],"log");
                        $this->payJoinfeeThree('软件服务费', $ooid, $post['price']);//微信支付改用第三方套皮调起
                    }
                }
            }else{
                $this->error('支付方式有问题',['ooid'=>$ooid]);
            }

        } else if ($post['terminal'] == 2) {
            if($post['price'] == 0){
                self::handle($ooid,0);
                $this->success('支付成功',['ooid'=>$ooid]);
                echo json_encode(['code'=>1,'data'=>[''],'ooid'=>$ooid]); //就是orderString 可以直接给客户端请求，无需再做处理。
            }else {
                //  $post['price'] = 0.01;
                //如果为2就是APP
                $alipay = new Alipay();
                $notice = $this->request->domain() . '/index.php/api/index/mhnotifyx';
                $alipay->pay('软件服务费', $ooid, $post['price'], $notice);   
            }
        }
    }
    
     public function getpaystatus()
     {
        $ooid=input('ooid');
        $order = Db::table('box_order')->where('out_trade_no', $ooid)->find();
        
        $status=$order['status'];
        if($status=='used'){
            $data['code']=1;
            $data['msg']='支付成功';
        }else{
             $data['code']=0;
            $data['msg']='支付失败';
        }
        echo json_encode($data);   
    }
    
    //第三方通联回调
    public function notifyxThreetttt()
    {
       // file_put_contents(__DIR__.'/0suc.txt', '' . var_export($_POST,true). "\r\n", FILE_APPEND);  //打印数组
        $postData = $_POST;
        log::write(["msg"=>"通联回调参数结构","psotdate"=>$postData],"log");
        if ($postData) {
            //如果成功返回了
            $out_trade_no = $postData['cusorderid'];
            $transaction_id = $postData['trxid'];
            $pedata = Db::table('box_prize_record')->field("id")->where('out_trade_no', $out_trade_no)->find();
             log::write(["msg"=>"难道是有中奖记录？","data"=>$pedata],"log");
            if(!$pedata){
                log::write(["msg"=>"这里进了没？","data"=>$pedata],"log");
                $this->handle($out_trade_no,$transaction_id);
            }
        }
        echo "success";
    }
    public function notifyx2()
    {
        log::write(["msg"=>"难不成回调成这个了？"],"log");
        $testxml = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true); //转成数组，
        log::write(["msg"=>"回调返回参数","res"=>$result],"log");
        if ($result) {
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];//商户订单号
            $transaction_id = $result['transaction_id'];//微信平台订单号
            $openid = $result['openid'];//openid
            // $this->handleRecharge2($out_trade_no, $transaction_id);  
            
            $recharge = Recharge::where('out_trade_no',$out_trade_no)->where('status','unpay')->find();
            if($recharge) {
               $user = User::where('id',$recharge->user_id)->find();
               $after_price = bcadd($user->balance,$recharge->pay_coin,2);
                $time = $result['time_end'];
                $str = substr($time,0,4).'-'.substr($time,4,2).'-'.substr($time,6,2).' '.substr($time,8,2).':'.substr($time,10,2).':'.substr($time,12,2);
               $recharge->pay_time = strtotime($str);
               $recharge->after_balace = $after_price;
               $recharge->transaction_id = $transaction_id;
               $recharge->status = 'used';
               $recharge->save(); 
               
              $ret = Db::table('box_balancelog')->insert([
                    'user_id'=> $recharge->user_id,
                    'beforemoney'=> $user->balance,
                    'aftermoney'=> $after_price,
                    'money'=> $recharge->pay_coin,
                    'bgexplain' => 'obcz',
                    'addtime' => time(),
              ]);
               
               $user->balance = $after_price;
               $user->save();
               
                $xml = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                echo $xml;   
                
                
                sleep(3);
                if($result){
                    file_put_contents("222222.txt",json_encode($result));
                    $s = Db::table('box_setting')->where('id', 1)->find();
                    if($s['is_fahuotongbu']){
                        $this->sendGoods($result['out_trade_no'],$result['transaction_id'],$result['openid']);
                    } 
                }
            }
            
            // Db::name('recharge')->where('out_trade_no',$out_trade_no)->where('status','unpay')->update([
            //   'transaction_id' =>  $transaction_id,
            //   'pay_time' => time(),
            //   'status' => 'used',
            // ]);
            
            
        }
    }
    public function notifyx()
    {
        log::write(["msg"=>"难不成回调成这个了？"],"log");
        $testxml = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true); //转成数组，
        log::write(["msg"=>"回调返回参数","res"=>$result],"log");
        if ($result) {
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];//商户订单号
            $transaction_id = $result['transaction_id'];//微信平台订单号
            $openid = $result['openid'];//openid
            $this->handle($out_trade_no, $transaction_id);  
        }
        $xml = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        echo $xml;
        
        sleep(3);
        if($result){
            $s = Db::table('box_setting')->where('id', 1)->find();
            if($s['is_fahuotongbu']){
                $this->sendGoods($result['out_trade_no'],$result['transaction_id'],$result['openid']);
            } 
        }
    }
    //第三方联速回调
    public function notifyxThree()
    {
        $postData = $_POST;
        log::write(["msg"=>"联速回调参数结构","psotdate"=>$postData],"log");
        if ($postData) {
            //如果成功返回了
            $out_trade_no = $postData['mch_order_no'];
            $transaction_id = $postData['pay_order_id'];
            $pedata = Db::table('box_prize_record')->field("id")->where('out_trade_no', $out_trade_no)->find();
             log::write(["msg"=>"难道是有中奖记录？","data"=>$pedata],"log");
            if(!$pedata){
                log::write(["msg"=>"这里进了没？","data"=>$pedata],"log");
                $this->handle($out_trade_no,$transaction_id);
            }
        }
        echo "ok";
    }
    //处理支付宝支付回调#todo
    public function mhnotifyx()
    {
        // $myfile = fopen("testfile.txt", "a");
        // fwrite($myfile, json_encode($_POST));
        if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
            self::handle2($_POST['out_trade_no'],$_POST['trade_no']);
            echo 'success';
        } else {
            echo 'fail';
        }
        // fclose($myfile);
    }

    //订单处理
    public function handle2($ooid,$tranid,$zb_rule_open = 0)
    {
        // log::write(["msg"=>"联速微信回调真的成功",'ooid'=>$ooid,'$tranid'=>$tranid],"log");
        $ret = Db::table('box_order')->where('out_trade_no', $ooid)->update(['status' => 'used', 'pay_time' => time(), 'alipay_trade_no' => $tranid/*,'pay_coin'=>100*/]);
        $order = Db::table('box_order')->where('out_trade_no', $ooid)->find();
        $s = Db::table('box_setting')->where('id', 1)->find();
        $user = Db::table('box_user')->where('id', $order['user_id'])->find();
        if (!empty($ret)) {
            log::write(['msg'=>"回调成功",'data'=>$ret],'error');
            $this->getOne($order,$user,$zb_rule_open);
            if ($order['xingshi'] != '0') {
                $res = Db::table('box_user')->where('id', $order['user_id'])->update(['money' => $user['money'] - $order['xingshi']]);
                log::write(['msg'=>"抵扣成功了吗？",'data'=>$res],'error');
                Db::table('box_moneylog')->insert([
                    'user_id' => $order['user_id'],
                    'beforemoney' => $user['money'],
                    'aftermoney' => ($user['money'] - $order['xingshi']) <= 0 ? 0 :  ($user['money'] - $order['xingshi']),
                    'money' => $order['xingshi'],
                    'bgexplain' => 'dikou',
                    'addtime' => time()
                ]);
            }
            if (!empty($user['pid']) && $order['pay_coin'] > 0) {
                //处理返佣,被邀请人首次开盒，赠送上级星石
                //1.查找是否是第一次开盒(如果邀请人是主播，就每次开盒都赠送主播用户)
                $u = Db::table('box_user')->where('id', $user['pid'])->find();
                if(!empty($u)){
                    if($u['anchor_switch'] == 1){
                        if($u['dd_switch'] == 1 && $u['dd_num'] >= 2 && $u['dd_num'] <= 10){
                            //主播
                            if($u['dd_residue'] == 1) {
                                if($u['dd_status'] == 1){
                                    
                                    
                                    $addStone = $order['pay_coin'] * ($s['pid_stone_anchor']/100) * 10;
                                    self::pigGetStone($addStone,$u);
                                    $pf = [
                                        'out_trade_no' => $order['out_trade_no'],
                                        'pay_time' => $order['pay_time'],
                                        'boxfl_id' => $order['boxfl_id'],
                                        'boxfl_name' => $order['boxfl_name'],
                                        'num' => $order['num'],
                                        'pay_coin' => $order['pay_coin'],
                                        'pay_part' => $addStone/10,
                                        'user_id' => $u['id'],
                                        'users_id' => $user['id'],
                                        'admin_id' => $u['admin_id'],
                                        'diaodan'=>1
                                    ];
                                    Db::table('box_anchor_pf')->insert($pf);
                                    log::write(['msg'=>"主播分成添加",'data'=>$pf],'error');  
                                    
                                    
                                    Db::table('box_user')->where('id', $user['pid'])->update([
                                         'dd_status' => 0,
                                         'dd_residue' => $u['dd_num'],
                                    ]);
                                }else {
                                    
                                    
                                    //掉单分成开始
                                    $addStone = $order['pay_coin'] * ($s['pid_stone_anchor']/100) * 10;
                                   // self::pigGetStone($addStone,$u);
                                    $pf = [
                                        'out_trade_no' => $order['out_trade_no'],
                                        'pay_time' => $order['pay_time'],
                                        'boxfl_id' => $order['boxfl_id'],
                                        'boxfl_name' => $order['boxfl_name'],
                                        'num' => $order['num'],
                                        'pay_coin' => $order['pay_coin'],
                                        'pay_part' => $addStone/10,
                                        'user_id' => $u['id'],
                                        'users_id' => $user['id'],
                                        'admin_id' => $u['admin_id'],
                                        'diaodan'=>0
                                    ];
                                    Db::table('box_anchor_pf')->insert($pf);
                                    log::write(['msg'=>"主播掉单分成添加",'data'=>$pf],'error');  
                                    //掉单分成结束
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    Db::table('box_user')->where('id', $user['pid'])->update([
                                         'dd_status' => 0,
                                         'dd_residue' => $u['dd_num'],
                                    ]);
                                }
                            }else {
                                if($u['dd_status'] == 1) {
                                    $addStone = $order['pay_coin'] * ($s['pid_stone_anchor']/100) * 10;
                                    self::pigGetStone($addStone,$u);
                                    $pf = [
                                        'out_trade_no' => $order['out_trade_no'],
                                        'pay_time' => $order['pay_time'],
                                        'boxfl_id' => $order['boxfl_id'],
                                        'boxfl_name' => $order['boxfl_name'],
                                        'num' => $order['num'],
                                        'pay_coin' => $order['pay_coin'],
                                        'pay_part' => $addStone/10,
                                        'user_id' => $u['id'],
                                        'users_id' => $user['id'],
                                        'admin_id' => $u['admin_id'],
                                        'diaodan'=>1
                                    ];
                                    Db::table('box_anchor_pf')->insert($pf);
                                    log::write(['msg'=>"主播分成添加",'data'=>$pf],'error');
                                    Db::table('box_user')->where('id', $user['pid'])->update([
                                         'dd_residue' => $u['dd_residue'] - 1,
                                    ]);
                                }else {
                                    $num = mt_rand(1,intval($u['dd_num']));
                                    $dd_residue = $u['dd_residue'];
                                    if($u['dd_residue'] <= 0) {
                                        $dd_residue = $u['dd_num'];
                                    }
                                    if($num == $u['dd_num']) {
                                        
                                        
                                        
                                  //掉单分成开始
                                    $addStone = $order['pay_coin'] * ($s['pid_stone_anchor']/100) * 10;
                                   // self::pigGetStone($addStone,$u);
                                    $pf = [
                                        'out_trade_no' => $order['out_trade_no'],
                                        'pay_time' => $order['pay_time'],
                                        'boxfl_id' => $order['boxfl_id'],
                                        'boxfl_name' => $order['boxfl_name'],
                                        'num' => $order['num'],
                                        'pay_coin' => $order['pay_coin'],
                                        'pay_part' => $addStone/10,
                                        'user_id' => $u['id'],
                                        'users_id' => $user['id'],
                                        'admin_id' => $u['admin_id'],
                                        'diaodan'=>0
                                    ];
                                    Db::table('box_anchor_pf')->insert($pf);
                                    log::write(['msg'=>"主播掉单分成添加",'data'=>$pf],'error');  
                                    //掉单分成结束
                                        
                                        
                                        
                                        
                                        
                                        
                                        Db::table('box_user')->where('id', $user['pid'])->update([
                                         'dd_status' => 1,
                                         'dd_residue' => $dd_residue - 1,
                                        ]);
                                    }else {
                                         $addStone = $order['pay_coin'] * ($s['pid_stone_anchor']/100) * 10;
                                        self::pigGetStone($addStone,$u);
                                        $pf = [
                                            'out_trade_no' => $order['out_trade_no'],
                                            'pay_time' => $order['pay_time'],
                                            'boxfl_id' => $order['boxfl_id'],
                                            'boxfl_name' => $order['boxfl_name'],
                                            'num' => $order['num'],
                                            'pay_coin' => $order['pay_coin'],
                                            'pay_part' => $addStone/10,
                                            'user_id' => $u['id'],
                                            'users_id' => $user['id'],
                                            'admin_id' => $u['admin_id'],
                                            'diaodan'=>1
                                        ];
                                        Db::table('box_anchor_pf')->insert($pf);
                                        log::write(['msg'=>"主播分成添加",'data'=>$pf],'error'); 
                                        
                                        Db::table('box_user')->where('id', $user['pid'])->update([
                                             'dd_residue' => $dd_residue - 1,
                                        ]);
                                    }   
                                }
                            }
                        }else {
                            $addStone = $order['pay_coin'] * ($s['pid_stone_anchor']/100) * 10;
                            self::pigGetStone($addStone,$u);
                            $pf = [
                                'out_trade_no' => $order['out_trade_no'],
                                'pay_time' => $order['pay_time'],
                                'boxfl_id' => $order['boxfl_id'],
                                'boxfl_name' => $order['boxfl_name'],
                                'num' => $order['num'],
                                'pay_coin' => $order['pay_coin'],
                                'pay_part' => $addStone/10,
                                'user_id' => $u['id'],
                                'users_id' => $user['id'],
                                'admin_id' => $u['admin_id'],
                                'diaodan'=>1
                            ];
                            Db::table('box_anchor_pf')->insert($pf);
                            log::write(['msg'=>"主播分成添加",'data'=>$pf],'error');   
                        }
                    }else {
                        $addStone = $order['pay_coin'] * ($s['pid_get_stone']/100) * 10;
                        $count = Db::table('box_order')->where('user_id', $user['id'])->count();
                        if ($count == 1){
                            self::pigGetStone($addStone,$u);
                        }
                    }
                }
            }
        }
    }

    //订单处理
    public function handle($ooid,$tranid,$zb_rule_open = 0)
    {
        // log::write(["msg"=>"联速微信回调真的成功",'ooid'=>$ooid,'$tranid'=>$tranid],"log");
        $ret = Db::table('box_order')->where('out_trade_no', $ooid)->update(['status' => 'used', 'pay_time' => time(), 'transaction_id' => $tranid/*,'pay_coin'=>100*/]);
        $order = Db::table('box_order')->where('out_trade_no', $ooid)->find();
        $s = Db::table('box_setting')->where('id', 1)->find();
        $user = Db::table('box_user')->where('id', $order['user_id'])->find();
        if (!empty($ret)) {
            log::write(['msg'=>"回调成功",'data'=>$ret],'error');
            $this->getOne($order,$user,$zb_rule_open);
            if ($order['xingshi'] != '0') {
                $res = Db::table('box_user')->where('id', $order['user_id'])->update(['money' => $user['money'] - $order['xingshi']]);
                log::write(['msg'=>"抵扣成功了吗？",'data'=>$res],'error');
                Db::table('box_moneylog')->insert([
                    'user_id' => $order['user_id'],
                    'beforemoney' => $user['money'],
                    'aftermoney' => ($user['money'] - $order['xingshi']) <= 0 ? 0 :  ($user['money'] - $order['xingshi']),
                    'money' => $order['xingshi'],
                    'bgexplain' => 'dikou',
                    'addtime' => time()
                ]);
            }
            if (!empty($user['pid']) && $order['pay_coin'] > 0) {
                //处理返佣,被邀请人首次开盒，赠送上级星石
                //1.查找是否是第一次开盒(如果邀请人是主播，就每次开盒都赠送主播用户)
                $u = Db::table('box_user')->where('id', $user['pid'])->find();
                if(!empty($u)){
                    if($u['anchor_switch'] == 1){
                        if($u['dd_switch'] == 1 && $u['dd_num'] >= 2 && $u['dd_num'] <= 10){
                            //主播
                            if($u['dd_residue'] == 1) {
                                if($u['dd_status'] == 1){
                                    $addStone = $order['pay_coin'] * ($s['pid_stone_anchor']/100) * 10;
                                    self::pigGetStone($addStone,$u);
                                    $pf = [
                                        'out_trade_no' => $order['out_trade_no'],
                                        'pay_time' => $order['pay_time'],
                                        'boxfl_id' => $order['boxfl_id'],
                                        'boxfl_name' => $order['boxfl_name'],
                                        'num' => $order['num'],
                                        'pay_coin' => $order['pay_coin'],
                                        'pay_part' => $addStone/10,
                                        'user_id' => $u['id'],
                                        'users_id' => $user['id'],
                                        'admin_id' => $u['admin_id'],
                                    ];
                                    Db::table('box_anchor_pf')->insert($pf);
                                    log::write(['msg'=>"主播分成添加",'data'=>$pf],'error');  
                                    Db::table('box_user')->where('id', $user['pid'])->update([
                                         'dd_status' => 0,
                                         'dd_residue' => $u['dd_num'],
                                    ]);
                                }else {
                                    Db::table('box_user')->where('id', $user['pid'])->update([
                                         'dd_status' => 0,
                                         'dd_residue' => $u['dd_num'],
                                    ]);
                                }
                            }else {
                                if($u['dd_status'] == 1) {
                                    $addStone = $order['pay_coin'] * ($s['pid_stone_anchor']/100) * 10;
                                    self::pigGetStone($addStone,$u);
                                    $pf = [
                                        'out_trade_no' => $order['out_trade_no'],
                                        'pay_time' => $order['pay_time'],
                                        'boxfl_id' => $order['boxfl_id'],
                                        'boxfl_name' => $order['boxfl_name'],
                                        'num' => $order['num'],
                                        'pay_coin' => $order['pay_coin'],
                                        'pay_part' => $addStone/10,
                                        'user_id' => $u['id'],
                                        'users_id' => $user['id'],
                                        'admin_id' => $u['admin_id'],
                                    ];
                                    Db::table('box_anchor_pf')->insert($pf);
                                    log::write(['msg'=>"主播分成添加",'data'=>$pf],'error');
                                    Db::table('box_user')->where('id', $user['pid'])->update([
                                         'dd_residue' => $u['dd_residue'] - 1,
                                    ]);
                                }else {
                                    $num = mt_rand(1,intval($u['dd_num']));
                                    $dd_residue = $u['dd_residue'];
                                    if($u['dd_residue'] <= 0) {
                                        $dd_residue = $u['dd_num'];
                                    }
                                    if($num == $u['dd_num']) {
                                        Db::table('box_user')->where('id', $user['pid'])->update([
                                         'dd_status' => 1,
                                         'dd_residue' => $dd_residue - 1,
                                        ]);
                                    }else {
                                         $addStone = $order['pay_coin'] * ($s['pid_stone_anchor']/100) * 10;
                                        self::pigGetStone($addStone,$u);
                                        $pf = [
                                            'out_trade_no' => $order['out_trade_no'],
                                            'pay_time' => $order['pay_time'],
                                            'boxfl_id' => $order['boxfl_id'],
                                            'boxfl_name' => $order['boxfl_name'],
                                            'num' => $order['num'],
                                            'pay_coin' => $order['pay_coin'],
                                            'pay_part' => $addStone/10,
                                            'user_id' => $u['id'],
                                            'users_id' => $user['id'],
                                            'admin_id' => $u['admin_id'],
                                        ];
                                        Db::table('box_anchor_pf')->insert($pf);
                                        log::write(['msg'=>"主播分成添加",'data'=>$pf],'error'); 
                                        Db::table('box_user')->where('id', $user['pid'])->update([
                                             'dd_residue' => $dd_residue - 1,
                                        ]);
                                    }   
                                }
                            }
                        }else {
                            $addStone = $order['pay_coin'] * ($s['pid_stone_anchor']/100) * 10;
                            self::pigGetStone($addStone,$u);
                            $pf = [
                                'out_trade_no' => $order['out_trade_no'],
                                'pay_time' => $order['pay_time'],
                                'boxfl_id' => $order['boxfl_id'],
                                'boxfl_name' => $order['boxfl_name'],
                                'num' => $order['num'],
                                'pay_coin' => $order['pay_coin'],
                                'pay_part' => $addStone/10,
                                'user_id' => $u['id'],
                                'users_id' => $user['id'],
                                'admin_id' => $u['admin_id'],
                            ];
                            Db::table('box_anchor_pf')->insert($pf);
                            log::write(['msg'=>"主播分成添加",'data'=>$pf],'error');   
                        }
                    }else {
                        $addStone = $order['pay_coin'] * ($s['pid_get_stone']/100) * 10;
                        $count = Db::table('box_order')->where('user_id', $user['id'])->count();
                        if ($count == 1){
                            self::pigGetStone($addStone,$u);
                        }
                    }
                }
            }
        }
    }
    protected function pigGetStone($addStone,$pidUser) {
        //2.根据后台设置返佣比例返佣,星石：金额=10:1
        $res = Db::table('box_user')->where('id', $pidUser['id'])->setInc('money', $addStone);
        if (!empty($res)) {
            Db::table('box_detailed')->insert([
                'user_id' => $pidUser['id'],
                'lytag' => 'kaihe',
                'lxtag' => 'stone',
                'stone' => $addStone,
                'laiyuan' => '好友首次开盒奖励' . $addStone .'星石',
                'jltime' => time()
            ]);
            Db::table('box_moneylog')->insert([
                'user_id' => $pidUser['id'],
                'beforemoney' => $pidUser['money'],
                'aftermoney' => $pidUser['money'] + $addStone,
                'money' => $addStone,
                'bgexplain' => 'pidback',
                'addtime' => time()
            ]);
        }
    }
    /**
     * 软件服务费（最新）
     * @param int $box_id 盲盒
     * @return mixed
     * @throws \Exception
     * @author 汇享 <43367628@qq.com>
     */
    public function getOne($order,$user,$zb_rule_open = 0)
    {
        // 查询该盲盒中的全部商品ID
        $goodsIds = Db::table('box_mhgoods')->where('boxfl_id', $order['boxfl_id'])->select();
        if (empty($goodsIds)) {
            throw new \Exception('奖品不足');
        }
        //#todo這裡要用盲盒商品設置的概率
        $box = Db::table('box_boxfl')->where('id', $order['boxfl_id'])->where('boxswitch', 1)->find();
        // 概率集合（比如这个盲盒里面有30个物品，最后总概率相加如果因为我计算错误导致>100%的话，那就默认从所有物品概率中的最大的那个值上面减去超出100%的部分，如果<100%那就默认从所有物品概率中的最大值的上面加上低于100%的部分）
        //如果用户是主播，并且主播必中未打开用主播概率
        if ($user['anchor_switch'] == 1 && $user['zb_switch'] != 1){
            $prizeRate = array_column($goodsIds, 'probability_anchor');
        }else {
            $prizeRate = array_column($goodsIds, 'probability');
        }
        // 商品ID集合
        $goodsList = array_column($goodsIds, 'id');
        $goodsId = array();
        if ($order['num'] == 1) {
            $id =  self::rand($prizeRate, $goodsList);
            array_push($goodsId, $id);
        } else {
            for ($n = 1; $n <= $order['num']; $n++) {
                $id =  self::rand($prizeRate, $goodsList);
                array_push($goodsId, $id);
            }
            //三抽及以上必中物品
            if(!empty($box["must_goods"]) && count($goodsId) >= 3){
                $must_goods = explode(',',$box["must_goods"]);
                if(count($must_goods) == 1){
                    $res = in_array($must_goods[0],$goodsId);
                    if(!$res){
                        $goodsId[2] = $must_goods[0];
                    }
                }else{
                    $isHave = false;
                    foreach($must_goods as $id){
                        if(in_array($id,$goodsId)){
                            $isHave = true;
                            break;
                        }
                    }
                    if(!$isHave){
                        //随机获取$must_goods数组中的一个值
                        $mustId = $must_goods[rand(0,count($must_goods)-1)];
                        $goodsId[2] = $mustId;
                    }
                }
            }
        }
        //主播规则开启
        if($user['zb_switch'] == 1 && $zb_rule_open == 1){
            $zb_goods = [];
            foreach ($goodsIds as $k => $v){
                if ($v['tag'] == 'supreme' || $v['tag'] == 'legend'){
                    $zb_goods[] = $v['id'];
                }
            }
            $zbId = $zb_goods[rand(0,count($zb_goods)-1)];
            $goodsId[rand(0,count($goodsId)-1)] = $zbId;
        }

        //拿到抽中的奖品ID查询对应商品
        $shops = [];
        foreach ($goodsId as $gid) {
            $shop = Db::table('box_mhgoods')->where('id', $gid)->find();
            array_push($shops, $shop);
        }
        // $shops = Db::table('box_mhgoods')->where('id','in',$goodsId)->select();
        log::write(['msg'=>"盲盒奖品",'data'=>$shops],'error');
        // print_r($shops);
        foreach ($shops as $key => $shop) {
            //处理抽到的奖品数据
            $image = explode(',', $shop['goods_images']);
            foreach ($image as $image_v) {
                $shop['imagess'][] = $image_v;
                $shop['images'][] = cdnurl($image_v, true);
            }
            // cdnurl($shop['goods_images'], true);
            //将抽到的商品写入仓库记录表
            // $ooid = 'ALDMH' . date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
            // $ooid = strval('ALDMH' . date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $key);
            list($msec, $sec) = explode(' ', microtime());
            $num = md5(floatval($msec) + floatval($sec).time());
            $ooid = strval('ALDMH' . date('Ymd') . substr(md5(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))).$num), 0, 8). $key);

            $data[] = [
                'boxfl_id' => $order['boxfl_id'],
                'order_id' => $ooid,
                'user_id' => $user['id'],
                'out_trade_no' => $order['out_trade_no'],
                'goods_id' => $shop['id'],
                'goods_name' => $shop['goods_name'],
                'goods_image' => $shop['imagess'][0],
                'goods_coin_price' => $shop['luckycoin'],
                'goods_rmb_price' => $shop['goods_pirce'],
                'status' => 'bag',
                'delivery_fee' => $shop['delivery_fee'],
                'create_time' => time(),
                'tag' => $shop['tag'],
            ];

            $mhlog[] = [
                'user_id' => $user['id'],
                'mhgoodsname' => $shop['goods_name'],
                'mhimage' => $shop['imagess'][0],
                'addtime' => time(),
                'mhgoods_id' => $shop['id'],
                'username' => $user['nickname']
            ];
        }
        log::write(['msg'=>"奖品log",'data'=>$mhlog],'error');
        log::write(['msg'=>"奖品记录",'data'=>$data],'error');
        Db::startTrans();
        try {
            $jp = Db::table('box_prize_record')->insertAll($data);
            log::write(['msg'=>"奖品列表添加",'data'=>$jp],'error');
            Db::table('box_mhlog')->insertAll($mhlog);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        $num = Db::table('box_card_list')->where('user_id', $this->auth->id)->where('status', 0)->count();
        // $this->success('重抽卡数量', $num);
        // $shops['ccknum'] = $num;
        //下级开盒，赠送上级星石
        return true;
    }

    public function zbOption($order,$user){
        $zb_rule = json_decode($user['zb_rule'],true);
        if($zb_rule['num']){
            $count = count($zb_rule['num']);
            $where = [
                'user_id'=>$user['id'],
                'boxfl_id'=>$order['boxfl_id'],
            ];
            $res = Db::table('box_order')->where($where)->order('id desc')->limit($count)->column('num');
            if($zb_rule['num'] == array_reverse($res)){
                return 1;
            }else {
                return 0;
            }
        }

    }




    public function getRecordList()
    {
        $out_trade_no = input('ooid');
        $res = Db::table('box_prize_record')->where('out_trade_no', $out_trade_no)->select();
        if($res){
            foreach ($res as $k=>$v){
                $res[$k]['goods_pirce'] = $v['goods_rmb_price'];
                $res[$k]['images'] = $v['goods_image'];
                $res[$k]['id'] = $v['goods_id'];
                $res[$k]['id_current'] = $v['id'];
            }
            $this->success('奖品列表',$res);
        }else {
            $this->error('没有奖品');
        }
    }
    /**
     * 试玩抽奖
     */
    public function SgetOne()
    {
        // $order = Db::table('box_order')->where('out_trade_no', $ooid)->find();
        // 查询该盲盒中的全部商品ID
        $goodsIds = Db::table('box_mhgoods')->where('boxfl_id', input('boxid'))->select();

        if (empty($goodsIds)) {
            throw new \Exception('奖品不足');
        }
        // 查询有效商品的概率信息标签:normal=高级,rare=稀有 ,supreme=史诗,legend=传说
        $box = Db::table('box_boxfl')->where('id', input('boxid'))->where('boxswitch', 1)->find();
        foreach ($goodsIds as &$goods) {
            if ($goods['tag'] == 'normal') {
                $goods['gl'] = $box['probability_gj'];
            } else if ($goods['tag'] == 'rare') {
                $goods['gl'] = $box['probability_xy'];
            } else if ($goods['tag'] == 'supreme') {
                $goods['gl'] = $box['probability_ss'];
            } else if ($goods['tag'] == 'legend') {
                $goods['gl'] = $box['probability_cs'];
            }
        }

        // 概率集合
        $prizeRate = array_column($goodsIds, 'gl');
        // 商品ID集合
        $goodsList = array_column($goodsIds, 'id');
        $goodsId = array();
        // print_r($goodsList);
        // exit;
        if (input('num') == 1) {
            $id =  self::rand($prizeRate, $goodsList);
            array_push($goodsId, $id);
        } else {
            for ($n = 1; $n <= input('num'); $n++) {
                $id =  self::rand($prizeRate, $goodsList);
                array_push($goodsId, $id);
            }
        }
        //拿到抽中的奖品ID查询对应商品
        // $gos = Db::table('box_mhgoods')->where('id', 'in', $goodsId)->select();
        // print_r($goodsId);
        $shops = [];
        foreach ($goodsId as $gid) {
            $shop = Db::table('box_mhgoods')->where('id', $gid)->find();
            array_push($shops, $shop);
        }
        // print_r($shops);
        foreach ($shops as &$shop) {
            //处理抽到的奖品数据
            $image = explode(',', $shop['goods_images']);
            foreach ($image as $image_v) {
                $shop['imagess'][] = $image_v;
                $shop['images'] = cdnurl($image_v, true);
            }
        }
        // $shop['']
        $this->success('试玩抽奖结果', $shops);
    }
    /*
    仓库开箱
    */
    public function getOnea()
    {
        $order = Db::table('box_yhbox')->where('id', input('id'))->find();
        $yhbox = Db::table('box_yhbox')->where('id', input('id'))->update(['status' => 2]);
        if(empty($yhbox)){
            $this->error('已经开启过了哦');
        }
        // 查询该盲盒中的全部商品ID
        $goodsIds = Db::table('box_mhgoods')->where('boxfl_id', $order['boxfl_id'])->select();
        // print_r($goodsIds);
        if (empty($goodsIds)) {
            throw new \Exception('奖品不足');
        }
        // 查询有效商品的概率信息标签:normal=高级,rare=稀有 ,supreme=史诗,legend=传说
        $box = Db::table('box_boxfl')->where('id', $order['boxfl_id'])->where('boxswitch', 1)->find();
        foreach ($goodsIds as &$goods) {
            if ($goods['tag'] == 'normal') {
                $goods['gl'] = $box['probability_gj'];
            } else if ($goods['tag'] == 'rare') {
                $goods['gl'] = $box['probability_xy'];
            } else if ($goods['tag'] == 'supreme') {
                $goods['gl'] = $box['probability_ss'];
            } else if ($goods['tag'] == 'legend') {
                $goods['gl'] = $box['probability_cs'];
            }
        }

        // 概率集合
        $prizeRate = array_column($goodsIds, 'gl');
        // 商品ID集合
        $goodsList = array_column($goodsIds, 'id');
        $goodsId = array();
        $id =  self::rand($prizeRate, $goodsList);
        array_push($goodsId, $id);
        $shops = [];
        foreach ($goodsId as $gid) {
            $shop = Db::table('box_mhgoods')->where('id', $gid)->find();
            array_push($shops, $shop);
        }
        foreach ($shops as &$shop) {
            //处理抽到的奖品数据
            $image = explode(',', $shop['goods_images']);
            foreach ($image as $image_v) {
                $shop['imagess'][] = $image_v;
                $shop['images'][] = cdnurl($image_v, true);
            }
            //将抽到的商品写入仓库记录表
            // $ooid = 'ALDMH' . date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
            list($msec, $sec) = explode(' ', microtime());
            $num = md5(floatval($msec) + floatval($sec).time());
            $ooid = 'ALDMH' . date('Ymd') . substr(md5(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))).$num), 0, 8);
            $data = [
                'boxfl_id' => $order['boxfl_id'],
                'order_id' => $ooid,
                'user_id' => $this->auth->id,
                'goods_id' => $shop['id'],
                'goods_name' => $shop['goods_name'],
                'goods_image' => $shop['imagess'][0],
                'goods_coin_price' => $shop['luckycoin'],
                'goods_rmb_price' => $shop['goods_pirce'],
                'status' => 'bag',
                'delivery_fee' => $shop['delivery_fee'],
                'create_time' => time(),
            ];
            Db::table('box_prize_record')->insert($data);
            $mhlog = [
                'user_id' => $this->auth->id,
                'mhgoodsname' => $shop['goods_name'],
                'mhimage' => $shop['imagess'][0],
                'addtime' => time(),
                'mhgoods_id' => $shop['id'],
                'username' => $this->auth->nickname
            ];
            Db::table('box_mhlog')->insert($mhlog);
        }
        $num = Db::table('box_card_list')->where('user_id', $this->auth->id)->where('status', 0)->count();
        $this->success('抽奖结果', ['data' => $shops, 'ccknum' => $num]);
    }
    /**
     * 随机
     * @param array $rate 中奖概率集合:
     * <pre>
     * $rate = [
     *     0 => 10, // 第二个奖品概率10%
     *     1 => 5.88, // 第二个奖品概率5.88%
     *     1 => 35.60, // 第二个奖品概率35.6%
     * ];
     * </pre>
     * @param array $goods 奖品集合，顺序与rate字段一致:
     * $rate = [
     *     0 => '第一个奖品',
     *     1 => '第二个奖品',
     *     2 => '第三奖品',
     * ];
     * @return mixed
     * @author fuyelk <fuyelk@fuyelk.com>
     * @date 2021/07/10 21:08
     */
    private static function rand($rate = [], $goods = [])
    {
        // 将数据按概率降序排序
        array_multisort($rate, SORT_DESC, $goods);
        foreach ($rate as &$item) {
            $item = round($item, 2) * 100; // 扩大100倍避免小数
        }

        //奖项的设置和概率可以手动设置化;
        $total = array_sum($rate);

        $notice = [];
        foreach ($rate as $key => $value) {
            $randNumber = mt_rand(1, $total);
            if ($randNumber <= $value) {
                $notice = $goods[$key];
                break;
            } else {
                $total -= $value;
            }
        }
        return $notice;
    }
    private static function randNew($rate = [], $goods = [])
    {
        // 将数据按概率降序排序
        array_multisort($rate, SORT_DESC, $goods);
        $total = array_sum($rate);

        if($total >100 ){
            $rate[0]-=($total-100);
        }
        if($total < 100 ){
            $num = count($rate);
            $rate[$num-1]+=(100-$total);
        }
        foreach ($rate as &$item) {
            $item = round($item, 2) * 100; // 扩大100倍避免小数
        }

        //奖项的设置和概率可以手动设置化;
        $total = array_sum($rate);
        $value = 0;
        $randNumber = mt_rand(1, $total);
        //dump($rate);die;
        foreach ($rate as $key => $val) {
            $value += $val;
            if ($value >= $randNumber) {
                return $goods[$key];
            }
        }
        return [];
    }
    /**
     * 图片上传
     */
    public function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/uploads/ 目录下
        // print_r($file = request()->file());
        // exit;
        if ($file == null) {
            exit(json_encode(array('code' => 1, 'msg' => '没有文件上传')));
        }
        $info = $file->validate(['size' => 10000000, 'ext' => 'jpg,png,gif'])->move('../public/uploads');
        if ($info) {
            // 成功上传后 获取上传信息
            $info = str_replace("\\", "/", $info->getSaveName());
            $img = '/uploads/' . $info;
            // exit(json_encode(array()));
            $this->success('上传成功', ['data' => $img, 'url' => Request::instance()->domain()  . $img]);
        } else {
            // 上传失败获取错误信息
            echo $file->getError();
        }
    }
    /**
     * 获取重抽卡数量
     */
    public function getCards()
    {
        $card = Db::table('box_card_list')->where('user_id', $this->auth->id)->where('status', 0)->select();
        $this->success('重抽卡', $card);
    }
    /**
     * 重抽卡使用
     */
    public function getCard()
    {
        //更改重抽卡状态 
        $ret = Db::table('box_card_list')->where('id', input('cardid'))->update([
            'status' => 1,
            'sytime' => time(),
        ]);
        // print_r($ret);
        // exit;
        $shop = Db::table('box_prize_record')->where('id', input('id'))->find();
        // echo 111;
        // exit;
        $data = [
            'boxfl_id' => $shop['boxfl_id'],
            'user_id' => $this->auth->id,
            'status' => 1,
            'addtime' => time()
        ];
        Db::table('box_yhbox')->insert($data);
        //删除盒柜内商品
        $ret = Db::table('box_prize_record')->where('id', input('id'))->delete();
        if (empty($ret)) {
            $this->error('使用失败');
        }
        $this->success('使用成功,请去盒柜重新开盒');
        // $order = Db::table('box_order')->where('out_trade_no', input('ooid'))->find();
        // $this->getOne(input('ooid'));
    }
    /**
     * 获取优惠券
     */
    public function getWcoupon()
    {
        $cou = Db::table('box_coupon_list')->where('user_id', $this->auth->id)->where('status', 0)->select();

        if (empty($cou)) {
            $this->error('暂无优惠券哦');
        } else {
            $id = [];
            foreach ($cou as &$c) {
                $id[] = $c['coupon_id'];
            }
            $coulist = Db::table('box_coupon')->where('id', 'in', $id)->where('end_time', '>', time())->select();
            foreach ($coulist as &$coupon) {
                $coupon['endtime_v'] = date('Y-m-d H:i:s', $coupon['end_time']);
            }

            $this->success('查询成功', ['list' => $coulist]);
        }
    }
    /**
     * 领取优惠券
     */
    public function receiveCoupon()
    {
        // 接收优惠券ID 可能是单个可能是多个
        $post = input('post.');
        //将优惠券ID单独拿出来
        $cid = $post['cid'];
        if (is_array($cid)) {
            $coupon = Db::table('box_coupon')->where('id', 'in', $cid)->select();
            //先循环查询到的优惠卷
            foreach ($coupon as $cou) {
                //然后在循环添加数据
                foreach ($cid as $id) {
                    // 根据优惠券ID查询对应的优惠券
                    $data = [
                        'user_id' => $this->auth->id,
                        'coupon_id' => $id,
                        'status' => 0
                    ];
                    if ($id == $cou['id']) {
                        $data['couname'] = $cou['couponname'];
                        $data['end_time'] = $cou['end_time'];
                        $ret = Db::table('box_coupon_list')->insert($data);
                    }
                }
            }
        } else {
            $coupon = Db::table('box_coupon')->where('id', $cid)->find();
            $data = [
                'user_id' => $this->auth->id,
                'coupon_id' => $cid,
                'couname' => $coupon['couponname'],
                'end_time'=>$coupon['end_time'],
                'status' => 0
            ];
            $ret = Db::table('box_coupon_list')->insert($data);
        }
        if (empty($ret)) {
            $this->error('领取失败请重试');
        } else {
            $this->success('领取成功', []);
        }
    }
    /*订单数量接口*/
    public function getNum()
    {
        $dfknum = Db::table('box_shoporder')->where('status', 'unpay')->where('user_id', $this->auth->id)->count();
        $dfhnum = Db::table('box_shoporder')->where('status', 'used')->where('user_id', $this->auth->id)->count();
        $yfhnum = Db::table('box_shoporder')->where('status', 'refund')->where('user_id', $this->auth->id)->count();
        // $dfhnum = Db::table('box_shoporder')->where('status','used')->count();
        $arr = [
            'dfk' => $dfknum,
            'dfh' => $dfhnum,
            'yfh' => $yfhnum,
        ];
        $this->success('订单数量', $arr);
    }
    public function getSite()
    {
        $site = Db::table('box_config')->where('name', 'name')->find();
        $this->success('盲盒名称', $site['value']);
    }
    public function getApp()
    {
        $s = Db::table('box_setting')->where('id', 1)->find();
        $this->success('APP下载地址', $s['appurl']);
    }
    public function getDomain()
    {
        $s = Db::table('box_setting')->where('id',1)->find();
        $this->success('域名', $s['domain']);
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    /****************************同步小程序发货信息*********************************/
    
     private function sendGoods($out_trade_no,$transaction_id,$openid){
        $order = Db::table('box_order')->field("user_id,boxfl_name,num,out_trade_no,transaction_id")->where('out_trade_no', $out_trade_no)->find();
        log::write(["msg"=>"发货订单信息","data"=>$order],"log");
        $tmp = $this->getAccessToken();
        $tmptoken = json_decode($tmp);
        $token = $tmptoken->access_token;
        $data['order_key']['order_number_type'] =2;
        $data['order_key']['transaction_id'] = $transaction_id;
        $data['logistics_type'] = 3;
        $data['delivery_mode'] = 1;
       // $data['shipping_list'][0]['item_desc'] = $order['boxfl_name'].'数量*'.$order['num'];
        
        $data['shipping_list'][0]['item_desc'] = '软件服务费';
        
        $data['upload_time'] = $this->formatTime();
        $data['payer']['openid'] = $openid;
        
        file_put_contents("55555.txt",json_encode($data));
        
        
        $url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=$token";
        log::write(["msg"=>"发货参数","data"=>$data],"log");
        $info = $this->http_request($url, json_encode($data,JSON_UNESCAPED_UNICODE), 'json');
        
        file_put_contents("fahuo.txt",$info);
        
        
        // 一定要注意转json，否则汇报47001错误
        //$tmpinfo = json_decode($info);
        log::write(["msg"=>"发货结果","data"=>$info],"log");
        return true;
    }
    /*获取access_token,不能用于获取用户信息的token*/
    public  function getAccessToken()
    {
        $s = Db::table('box_setting')->where('id', 1)->find();
        $appid = $s['mpappid'];
        $secret = $s['mpappkey'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }
    //图片合法性验证
    public function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json'
            ));
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);

        return $output;
    }
    private function formatTime(){
        $dateTime = new \DateTime("now",new \DateTimeZone("Asia/Shanghai"));
        // 获取时区偏移量并转换为格式化字符串
        $timeZoneOffset = $dateTime->format("P");
        // 格式化日期时间
        $formattedDateTime = $dateTime->format("Y-m-d\TH:i:s.u") . $timeZoneOffset;
        return $formattedDateTime;
    }

 
    
    
  /****************************同步小程序发货信息*********************************/
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
